package com.ai.web.weixin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.ai.web.util.AddSHA1;
import com.ai.web.weixin.message.util.MessageUtil;

/**
 * 核心请求处理类
 * 
 * @author wushen
 */
public class WeixinServlet extends HttpServlet {
	
	private static final long serialVersionUID = 4440739483644821986L;

	private static Logger logger = Logger.getLogger(WeixinServlet.class);
	
	private static final String TOKEN = "WSLJHaoHao";
	
	/**
	 * 确认请求来自微信服务器
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		
		logger.info("[WeiXin] checkSignature signature=" + signature
				+ " timestamp=" + timestamp
				+ " nonce=" + nonce
				+ " echostr=" + echostr);
		
		String token = TOKEN;
		String[] args = new String[]{token, timestamp, nonce};
		Arrays.sort(args);
		
		String tmpStr = "";
		for (String arg : args) {
			tmpStr += arg;
		}
		tmpStr = AddSHA1.SHA1(tmpStr);
		
		logger.info("[WeiXin] checkSignature tmpStr=" + tmpStr + " signature=" + signature);
		
		PrintWriter out = response.getWriter();
		if (tmpStr.equals(signature)) {
			out.print(echostr);
		}
		out.close();
		out = null;
	}

	/**
	 * 处理微信服务器发来的消息
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Map<String, String> msgMap = MessageUtil.parseXml(request);
			logger.info("recTextMsg = " + msgMap);
			
			String respMessage = MessageDispatch.dispatch(msgMap);
			if (respMessage != null) {
				// 响应消息  
		        PrintWriter out = response.getWriter();  
		        out.print(respMessage);  
		        out.close();
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

}

